package org.lee.springcloud.gateway.filters;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;

/**
 * @author jackielee
 * @version 1.0
 * @description MyFilter
 * @date 2021/3/12
 **/
public class TokenFilter extends ZuulFilter {
    private final Logger logger = LoggerFactory.getLogger(TokenFilter.class);

    @Override
    public String filterType() {
        return "pre"; // 定义filter类型，pre、route、post、error 4种
    }

    @Override
    public int filterOrder() {
        return 0; // filter顺序，越小越先执行
    }

    @Override
    public boolean shouldFilter() {
        return true; // 是否要执行该filter，false不执行
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        logger.info(String.format( ">>>>>>> TokenFilter %s,%s", request.getMethod(), request.getRequestURL().toString()));

        String token = request.getParameter("token"); // 请求参数token
        if(StringUtils.isNotBlank(token)){
            context.setSendZuulResponse(true); // 对请求进行路由
            context.setResponseStatusCode(200);
            context.set("success", true);
        }else{
            context.setSendZuulResponse(false); // 不对请求进行路由
            context.setResponseStatusCode(401);
            context.setResponseBody("token is empty");
            context.set("success", false);
        }
        return null; // 执行具体操作
    }
}
